package myadmin.jtthink.com.MyServices;

import myadmin.jtthink.com.Mapper.RoleAccessMapper;
import myadmin.jtthink.com.Models.RoleAccessModel;
import myadmin.jtthink.com.Models.UserAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class RUserService implements UserDetailsService {
    @Autowired
    RoleAccessMapper roleAccessMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserAuth userAuth=new UserAuth(s,"",this.getAuthorities(s));
        return userAuth;
    }
    private Collection<GrantedAuthority> getAuthorities(String user){
        List<RoleAccessModel> roleAccessModels=roleAccessMapper.getUserRoleAccess(user);
        StringBuffer stringBuffer=new StringBuffer();
        for(RoleAccessModel roleAccessModel:roleAccessModels){
            stringBuffer.append(roleAccessModel.getRoleName())
                    .append(",")
                    .append(roleAccessModel.getAccessName())
                    .append(",");
        }
        return AuthorityUtils.commaSeparatedStringToAuthorityList(
                stringBuffer.deleteCharAt(stringBuffer.length()-1).toString()
        );

    }

}
